//
//  MatchViewController.m
//  us
//
//  Created by karry on 2025/4/2.
//

#import "MatchViewController.h"
#import "MatchAboutUsViewController.h"
#import "IQKeyboardManager.h"


@interface MatchViewController ()


@property (nonatomic, strong) UIImageView *gifImgView;

@property (nonatomic ,strong) UILabel *titleLab;
@property (nonatomic, strong) UIButton *numberBtn;

@property (nonatomic, strong) UITextField *matchTF;

@property (nonatomic, strong) UIButton *matchBtn;

@property (nonatomic, strong) NSString *number;

@end

@implementation MatchViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 20 + 56 + 20;
    IQKeyboardManager.sharedManager.enableAutoToolbar = YES;
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = NO;
    IQKeyboardManager.sharedManager.enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 10;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 20 + 56 + 20;
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = UIColor.subMainBgColor;
    
    [self initLayout];
    
    [self setupRAC];
    
    [self.view layoutIfNeeded];
     
    [self getInvitationCode];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
}

- (void)getInvitationCode {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:USUser.user.userId forKey:@"userId"];
    [[EMNetWork shareManager]em_post:API_GetInvitationCode params:params hud:@"" showError:YES success:^(EMApiModel *api) {
        if (api.success == NO) {
            return;
        }
        NSString *invitationCode = NotNullStr(api.data[@"invitationCode"], @"");

        self.number = invitationCode;
        [self.numberBtn setTitle:invitationCode forState:0];

 
        [self.view endEditing:YES];
 
     
    } fail:^{
        
    }];
}



- (void)setupRAC{
    
    @weakify(self)
    [[self.matchTF rac_signalForControlEvents:UIControlEventEditingDidBegin]subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        self.matchTF.layer.borderWidth = 3;
        self.matchTF.layer.borderColor = UIColor.brightBorderColor.CGColor;
    }];
    
    [[self.matchTF rac_signalForControlEvents:UIControlEventEditingDidEnd]subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        self.matchTF.layer.borderWidth = 0;
        self.matchTF.layer.borderColor = [UIColor clearColor].CGColor;
    }];
    
    
    RAC(self.matchBtn,enabled) = [RACSignal combineLatest:@[[self.matchTF rac_textSignal]] reduce:^id (NSString *text){
        
        return @(text.length > 0);
    }];
    
    
}

- (void)gotoMatch {
    MatchAboutUsViewController *vc = [[MatchAboutUsViewController alloc]init];
    vc.invitationCode = self.self.matchTF.text ?:@"";
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)copyAction {
    // 把文本设置到通用剪贴板
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = self.number?:@"";

    [self.view makeToast:@"复制成功"];
}

- (void)initLayout{
    
    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:self.view.bounds];
    scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:scrollView];
    
    UIView *contentView = [UIView new];
    [scrollView addSubview:contentView];
    
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(scrollView);
        make.edges.equalTo(scrollView); // 等价于 top/left/right/bottom 全部为 0
    }];
    
    [contentView addSubview:self.gifImgView];
    [self.gifImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(28);
        make.left.mas_offset(32);
        make.right.mas_offset(-32);
        make.height.mas_equalTo(127);
    }];
    
    [contentView addSubview:self.titleLab];
    [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(contentView);
        make.top.equalTo(self.gifImgView.mas_bottom).offset(32);
    }];
    
    [contentView addSubview:self.numberBtn];
    [self.numberBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(contentView);
        make.top.equalTo(self.titleLab.mas_bottom).offset(12);
    }];
    
    [contentView addSubview:self.matchTF];
    [self.matchTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.numberBtn.mas_bottom).offset(39);
        make.left.mas_offset(32);
        make.right.mas_offset(-32);
        make.height.mas_equalTo(64);
        make.bottom.mas_offset(-20);
    }];
    
    [self.view addSubview:self.matchBtn];
    [self.matchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.greaterThanOrEqualTo(self.matchBtn.mas_bottom).offset(60).priorityHigh();
        make.left.mas_equalTo(self.view.mas_safeAreaLayoutGuideLeft).offset(32);
        make.right.mas_equalTo(self.view.mas_safeAreaLayoutGuideRight).offset(-32);
        make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-20);
        make.height.mas_equalTo(56);
    }];
    
    
}

- (void)keyboardWillHide:(NSNotification *)notification {
    
    NSDictionary *userInfo = notification.userInfo;
    NSTimeInterval duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [self.matchBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_safeAreaLayoutGuideLeft).offset(32);
        make.right.mas_equalTo(self.view.mas_safeAreaLayoutGuideRight).offset(-32);
        make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(-20);
        make.height.mas_equalTo(56);
    }];
    
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
    
    
}
- (void)keyboardWillShow:(NSNotification *)notification {
    
    NSDictionary *userInfo = notification.userInfo;
    CGRect keyboardFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    [self.matchBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_safeAreaLayoutGuideLeft).offset(32);
        make.right.mas_equalTo(self.view.mas_safeAreaLayoutGuideRight).offset(-32);
        make.bottom.equalTo(self.view).offset(-keyboardFrame.size.height - 20);
        make.height.mas_equalTo(56);
    }];

    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
    
}

- (UIImageView *)gifImgView {
    if (_gifImgView == nil) {
        _gifImgView = [[UIImageView alloc] init];
        NSString *path = [[NSBundle mainBundle] pathForResource:@"match_1" ofType:@"gif"];
        NSURL *fileURL = [NSURL fileURLWithPath:path];
        [_gifImgView sd_setImageWithURL:fileURL];
     }
    return _gifImgView;
}


- (UITextField *)matchTF {
    if (_matchTF == nil) {
        _matchTF = [UITextField new];
        _matchTF.layer.cornerRadius = 14;
        _matchTF.placeholder = @"点击输入匹配码";
        _matchTF.textColor = UIColor.titleColor;
        _matchTF.font = [UIFont systemFontOfSize:20 weight:UIFontWeightMedium];
        _matchTF.backgroundColor = [UIColor jk_colorWithHex:0xEFEFE8];
        _matchTF.textAlignment = NSTextAlignmentCenter;
    }
    return _matchTF;
}
- (UILabel *)titleLab {
    if (_titleLab == nil) {
        _titleLab = [[UILabel alloc]init];
        _titleLab.text = @"添加另一半开启US生活";
        _titleLab.textAlignment = NSTextAlignmentCenter;
        _titleLab.textColor = [UIColor jk_colorWithHex:0x1c1c1c andAlpha:0.5];
        _titleLab.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    }
    return _titleLab;
}
 
- (UIButton *)numberBtn {
    if (_numberBtn == nil) {
        _numberBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _numberBtn.layer.cornerRadius = 14;
        _numberBtn.clipsToBounds = YES;
        [_numberBtn.titleLabel setFont:[UIFont systemFontOfSize:28 weight:UIFontWeightMedium]];
        [_numberBtn setTitleColor:[UIColor jk_colorWithHex:0x1c1c1c] forState:0];
        [_numberBtn setImage:[UIImage imageNamed:@"copy"] forState:0];
        [_numberBtn setSemanticContentAttribute:UISemanticContentAttributeForceRightToLeft];
        [_numberBtn addTarget:self action:@selector(copyAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _numberBtn;
}

- (UIButton *)matchBtn {
    if (_matchBtn == nil) {
        _matchBtn = [UIButton us_fillButtonWithTitle:@"去匹配"];
        _matchBtn.layer.cornerRadius = 14;
        [_matchBtn addTarget:self action:@selector(gotoMatch) forControlEvents:UIControlEventTouchUpInside];
    }
    return _matchBtn;
}
@end
